package com.situ.mall.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.situ.mall.common.entity.*;
import com.situ.mall.common.mapper.*;
import com.situ.mall.common.service.IOrderInfoService;
import com.situ.mall.common.util.RequestUtil;
import com.situ.mall.common.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author JavaWizard
 * @since 2023-09-25
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private LocationMapper locationMapper;
    @Autowired
    private OrderLocationMapper orderLocationMapper;

    //保存订单
    //一条订单主表，对应多条订单明细表，对应一条订单收货地址表
    @Override
    @Transactional(rollbackFor = Exception.class) //让方法在一个事务中运行，要么都成功，要么都失败
    public PayVO saveOrder(String ids, Integer locationId) {

        //返回的PayVO
        PayVO payVO = new PayVO();

        //获取当前登陆对象
        Member m = (Member)RequestUtil.getCurrent();

        //创建一个orderInfo对象，保存进数据库
        OrderInfo oi = new OrderInfo();
        //生成订单号（保证唯一）
        oi.setCode("0-" + System.currentTimeMillis());
        oi.setCreateTime(LocalDateTime.now());//生成订单时间
        oi.setStatus("1");//生成订单状态
        oi.setMemberId(m.getId());//放入所属用户id
        BigDecimal sum = new BigDecimal("0");
        //算总价格，遍历出来每一个id都是一条购物车id
        for (String cid : ids.split(",")) {
            //根据购物车id查购物车
            Cart c = cartMapper.selectById(Integer.parseInt(cid));
            //再根据购物车中商品id查商品
            Product p = productMapper.selectById(c.getProductId());
            //算总价：单价x数量
            sum = sum.add(p.getPrice().multiply(new BigDecimal(c.getAmount())));
        }
        oi.setPrice(sum);//放入该订单总价格
        baseMapper.insert(oi);

        //PayVO里的CartVO集合
        List<CartVO> cartVOS = new ArrayList<>();

        //创建多个orderDetail对象，保存进数据库
        for (String cid : ids.split(",")) {
            OrderDetail od = new OrderDetail();
            //根据购物车id查购物车
            Cart c = cartMapper.selectById(Integer.parseInt(cid));
            //再根据购物车中商品id查商品
            Product p = productMapper.selectById(c.getProductId());

            //给CartVO赋值并放到集合里
            CartVO cartVO = new CartVO();
            BeanUtils.copyProperties(p, cartVO);
            cartVO.setAmount(c.getAmount());
            cartVOS.add(cartVO);

            od.setOrderId(oi.getId());//主表id
            od.setProductId(p.getId());//商品id
            od.setAmount(c.getAmount());//商品数量
            od.setOldPrice(p.getPrice());//商品单价
            orderDetailMapper.insert(od);
        }

        //创建一个orderLocation对象，保存进数据库
        //根据用户地址id查地址
        Location l = locationMapper.selectById(locationId);
        OrderLocation ol = new OrderLocation();
        //把选中的用户地址对象中的各项属性拷贝到订单地址对象中
        BeanUtils.copyProperties(l,ol);//用时注意导包问题
        //ol的id靠自增生成，拷贝完后需要置空！！！！
        ol.setId(null);
        ol.setOrderId(oi.getId());//主表id
        orderLocationMapper.insert(ol);

        //把购物车表中原来的数据删除
        for (String cid : ids.split(",")) {
            cartMapper.deleteById(Integer.parseInt(cid));
        }

        //给PayVO赋值并返回
        payVO.setId(oi.getId());
        payVO.setCode(oi.getCode());
        payVO.setCreateTime(oi.getCreateTime());
        payVO.setPrice(oi.getPrice());
        payVO.setOrderLocation(ol);
        payVO.setCartVOS(cartVOS);
        return payVO;

    }

    //查询订单
    @Override
    public TableVO table(Integer page, Integer limit, String memberName, String tel) {
        //PageHelper 分页小工具
        PageHelper.startPage(page, limit);
        //上边这行代码后跟的第一次查数据库是分页查询，只生效一次！！！
        List<OrderVO> list = baseMapper.list(memberName, tel);
        return TableVO.data(list);
    }

    //查该会员所有订单
    @Override
    public TableVO selectByMemberId(String status, String keyword, Integer page, Integer limit, Integer memberId) {
        //分页
        PageHelper.startPage(page, limit);
        //查询订单
        List<PersonalOrderVO> personalOrderVOS = baseMapper.all(status, memberId);
        //遍历查出来的订单，给每个订单里的最后一个商品添加flag属性
        for (PersonalOrderVO personalOrderVO : personalOrderVOS) {
            List<OrderDetailVO> voList = personalOrderVO.getOrderDetailVOS();
            int size = voList.size();
            for (OrderDetailVO orderDetailVO : voList) {
                if (size == 1){
                    orderDetailVO.setFlag("111");
                    break;
                }
                size--;
            }
        }
        //放到表格里
        return TableVO.data(personalOrderVOS);
    }

}
